﻿using Microsoft.AspNetCore.Http;
using System;
using System.IO;
using System.Linq;

namespace Batman.Cms.Core.Utils
{
    public class ImageUtil
    {
        /// <summary>
        /// 允许上传的图片格式
        /// </summary>
        public static readonly string[] ExtensionNameAllowed;

        static ImageUtil()
        {
            ExtensionNameAllowed = new string[] { ".jpg", ".jpeg", ".png", ".gif" };
        }

        /// <summary>
        /// 保存图片
        /// </summary>
        /// <param name="imageStream"></param>
        /// <param name="extensionName"></param>
        /// <param name="success"></param>
        /// <returns></returns>
        public static string SaveImage(Stream imageStream, string extensionName, string basePath, out bool success)
        {
            success = false;
            if (!ExtensionNameAllowed.Contains(extensionName))
                return "文件格式不允许";

            var dest = $"images/{DateTime.Now.ToString("yyyyMM/yyyyMMdd")}";
            var physical = $"{basePath}/wwwroot/{dest}";

            if (!Directory.Exists(physical))
                Directory.CreateDirectory(physical);

            var filename = $"{Guid.NewGuid().ToString()}{extensionName}";
            physical = $"{physical}/{filename}";

            byte[] buffer;
            if (imageStream is MemoryStream)
            {
                buffer = ((MemoryStream)imageStream).ToArray();
            }
            else
            {


                buffer = new byte[imageStream.Length];
                imageStream.Write(buffer, 0, (int)imageStream.Length);
            }

            File.WriteAllBytes(physical, buffer);
            success = true;

            return $"/{dest}/{filename}";
        }


        /// <summary>
        /// 保存图片
        /// </summary>
        /// <param name="imageStream"></param>
        /// <param name="extensionName"></param>
        /// <param name="success"></param>
        /// <returns></returns>
        public static string SaveImage(IFormFile file, string extensionName, string basePath, out bool success)
        {
            success = false;
            if (!ExtensionNameAllowed.Contains(extensionName))
                return "文件格式不允许";

            var dest = $"images/{DateTime.Now.ToString("yyyyMM/yyyyMMdd")}";
            var physical = $"{basePath}/wwwroot/{dest}";

            if (!Directory.Exists(physical)) Directory.CreateDirectory(physical);

            var filename = $"{Guid.NewGuid().ToString()}{extensionName}";
            physical = $"{physical}/{filename}";

            using (var stream = new FileStream(physical, FileMode.Create))
            {
                file.CopyTo(stream);
            }

            success = true;

            return $"/{dest}/{filename}";
        }
    }
}
